<style lang="less">

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .f-w70 {
    width: 70%;
  }
  .el-table {
    flex: 1;
    .el-icon-check {
      display: none;
    }
    .current-row {
      .el-icon-check {
        display: inline-block;
      }
    }
  }
</style>

<template>
  <section>
    <!--工具条-->
    <el-form ref="searchConditionForm" label-position="right" :model="searchConditionForm" style="background-color: #F2F2F2">
      <el-row style="padding-top: 10px">
        <el-col :span="16">
          <el-form-item labelWidth="20px" style="margin-bottom: 10px">
            <el-col :span="4">
              <el-select v-model="searchConditionForm.dateType" style="width: 95%" placeholder="日期类型">
                <el-option label="发车日期" value="departureDate"></el-option>
                <el-option label="报账确认日期" value="affirmTime"></el-option>
                <el-option label="报账审核日期" value="auditTime"></el-option>
              </el-select>
            </el-col>
            <el-col :span="14">
              <el-row style="width: 98%">
                <el-col :span="11">
                  <el-date-picker type="date" placeholder="选择开始日期" v-model="searchConditionForm.dateTypeValueStart" style="width: 100%;"></el-date-picker>
                </el-col>
                <el-col style="text-align: center" :span="2">-</el-col>
                <el-col :span="11">
                  <el-date-picker type="date" placeholder="选择结束日期" v-model="searchConditionForm.dateTypeValueEnd" style="width: 100%;"></el-date-picker>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="6">
              <el-button-group>
                <el-button style="padding-left: 5px;padding-right: 5px" @click="searchToday">今日</el-button>
                <el-button style="padding-left: 5px;padding-right: 5px" @click="searchWeek">近一周</el-button>
                <el-button style="padding-left: 5px;padding-right: 5px" @click="searchMonth">近一月</el-button>
              </el-button-group>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item labelWidth="80px" label="报账状态" style="margin-bottom: 10px">
            <el-select v-model="searchConditionForm.status" style="width: 95%"
                       placeholder="请选择报账状态">
              <el-option
                v-for="orderSource in $store.getters.RENDER_ACCOUNT_STATUS"
                :label="orderSource.cnDictValname"
                :key="orderSource.dictVal"
                :value="orderSource.dictVal"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item class="f-mb10" labelWidth="20px" style="margin-bottom: 10px">
            <el-col :span="4">
              <el-select v-model="searchConditionForm.driverOrVehicle" style="width: 95%" placeholder="车牌或司机">
                <el-option label="车牌号" value="plateNumber"></el-option>
                <el-option label="司机姓名" value="driverName"></el-option>
              </el-select>
            </el-col>
            <el-col :span="14">
              <el-input v-model="searchConditionForm.driverOrVehicleValue"
                        placeholder="请输入查询条件"></el-input>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item labelWidth="80px" label="发车站点" style="margin-bottom: 10px">
            <el-input v-model="searchConditionForm.departureOrgName" style="width: 95%"
                      placeholder="请输入发车站点"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 操作 -->
    <el-col :span="24" style="margin-bottom: 10px;margin-top: 10px">
      <el-button type="primary" @click="modifyStatus(102016002,'已确认')" :disabled="!toAffirm">费用确认</el-button>
      <el-button type="primary" @click="modifyStatus(102016001,'新建')"  :disabled="!cancelAffirm">取消确认</el-button>
      <el-button type="primary" @click="modifyStatus(102016003,'待审核')"  :disabled="!toAudit">提交审核</el-button>
      <el-button type="danger" @click="modifyStatus(102016002,'已确认')" :disabled="!cancelAudit">取消提交审核</el-button>
      <el-button type="primary" @click="modifyStatus(102016002,'已确认')"   :disabled="!toAffirmAudit">确认审核</el-button>
      <el-button type="primary" @click="modifyStatus(102016001,'新建')"   :disabled="!toRefuseAudit">驳回</el-button>
      <el-button type="primary" @click="modifyStatus(102016003,'待审核')"  :disabled="!toCancelAffirmAudit">取消确认审核</el-button>
      <el-button type="primary" @click="resetCondition" style="margin-left:10px;float: right">重置</el-button>
      <el-button type="primary" @click="getTableData" style="float: right">查询</el-button>
      <el-button type="primary" :disabled="true" style="float: right">导出</el-button>
    </el-col>
    <!--列表-->
    <el-table :data="tableData" highlight-current-row border  @current-change="selsChange" show-summary :summary-method="getSummariesAccount"
              v-loading="listLoading" style="width: 100%;" max-height="640">
      <!--<el-table-column type="selection" width="50">-->
      <!--</el-table-column>-->
      <el-table-column
        label="选中"
        width="50">
        <template slot-scope="scope">
          <i class="el-icon-check"></i>
        </template>
      </el-table-column>
      <el-table-column prop="departureDate" label="发车日期" width="120"  align="center">
        <template slot-scope="scope">
          <label v-if="scope.row.departureDate">{{scope.row.departureDate.substring(0, 10)}}</label>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip fit prop="loadingListNumber" label="装车单号" width="100" header-align="center">
      </el-table-column>
      <el-table-column prop="statusName" label="报账状态" width="100"  align="center">
      </el-table-column>
      <el-table-column prop="affirmTime" label="报账确认日期" width="120"  align="center">
        <template slot-scope="scope">
          <label v-if="scope.row.affirmTime">{{scope.row.affirmTime.substring(0, 10)}}</label>
        </template>
      </el-table-column>
      <el-table-column prop="auditTime" label="报账审核日期" width="120"  align="center">
        <template slot-scope="scope">
          <label v-if="scope.row.auditTime">{{scope.row.auditTime.substring(0, 10)}}</label>
        </template>
      </el-table-column>
      <el-table-column prop="accountTotal" label="报账合计" width="100"  align="center">
      </el-table-column>
      <el-table-column prop="departureOrgName" label="发车站点" width="120"  align="center">
      </el-table-column>
      <el-table-column prop="loadingListRouteChainName" label="运输路线" show-overflow-tooltip fit min-width="100"  align="center">
      </el-table-column>
      <el-table-column prop="plateNumber" label="车牌号" width="130"  align="center">
      </el-table-column>
      <el-table-column prop="driverName" label="司机/联系电话" width="130"  align="center">
        <template slot-scope="scope">
          <label>{{scope.row.driverName}}<br>{{scope.row.driverPhone}}
          </label>
        </template>
      </el-table-column>
      <el-table-column prop="organizationName" label="实际票数/件数/体积/重量" width="200"  align="center">
        <template slot-scope="scope">
          <label>{{scope.row.poll}}票/{{scope.row.totalAmount}}件/{{scope.row.totalWeight}}吨/{{scope.row.totalVolume}}方
          </label>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button  type="primary"  @click="handleAccountDetail(scope.row)">报账明细 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>
    <!--报账明细弹窗-->
    <el-dialog title="报账明细" top="2%" size="large" :visible.sync="accountingDetailVisible"  @close='detailListCancel' :close-on-click-modal="false">
      <el-row>
        <!--订单费用明细-->
        <el-col :span="24">
          <div style="border: 1px solid #F2F2F2;">
            <div style="background-color: #F2F2F2;padding: 10px">
              <label style="height: 35px;font-weight: 700">订单费用明细</label>
            </div>
            <div style="padding: 0px 10px">
              <el-table :data="tableDataDetail" highlight-current-row border height="350"  show-summary :summary-method="getSummariesDetail"
                        v-loading="listLoadingDetail" style="width: 100%;margin-bottom: 10px;margin-top: 10px">
                <el-table-column type="index" width="50" label="序号" align="center">
                </el-table-column>
                <el-table-column prop="departureDate" label="发运日期" width="120"  align="center">
                  <template slot-scope="scope">
                    <label v-if="scope.row.shipmentsDate">{{scope.row.shipmentsDate.substring(0, 10)}}</label>
                  </template>
                </el-table-column>
                <el-table-column prop="orderNumber" label="订单号" width="150"  align="center">
                </el-table-column>
                <el-table-column prop="cargoName" label="货物名称" width="150"  align="center">
                </el-table-column>
                <el-table-column prop="accountTotal" label="实际件数/重量/体积" width="200"  align="center">
                  <template slot-scope="scope">
                    <label>{{scope.row.actualAmount}}件/{{scope.row.actualWeight}}吨/{{scope.row.actualVolume}}方
                    </label>
                  </template>
                </el-table-column>
                <el-table-column prop="departureOrgName" label="收货人/电话" min-width="200"  align="center">
                  <template slot-scope="scope">
                    <label>{{scope.row.sendContactName}} {{scope.row.sendContactPhone}}
                    </label>
                  </template>
                </el-table-column>
                <el-table-column prop="sendAddress" label="收货区域" min-width="200"  align="center">
                </el-table-column>
                <el-table-column prop="totalFees" label="费用小计" min-width="120"  align="center">
                </el-table-column>
                <el-table-column prop="remark" label="摘要" min-width="120"  align="center">
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template slot-scope="scope">
                    <el-button  type="primary"  @click="handleAccountCostList(scope.row)">费用记录 </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!--工具条-->
              <el-col :span="24" class="toolbar" style="margin-top: 10px">
                <el-pagination
                  :current-page="currentPageDetail"
                  :page-size="pageSizeDetail"
                  @size-change="handleSizeChangeDetail"
                  @current-change="handleCurrentChangeDetail"
                  layout="total,sizes,prev, pager, next, jumper"
                  :total="totalDetail" style="float: right">
                </el-pagination>
              </el-col>
            </div>
          </div>
        </el-col>
        <!--其他费用明细-->
        <el-col :span="24" style="margin-top: 10px;padding-bottom: 10px">
          <div style="border: 1px solid #F2F2F2;">
            <div style="background-color: #F2F2F2;padding: 10px">
              <label style="height: 35px;font-weight: 700">其他费用明细</label>
            </div>
            <div style="padding: 0px 10px">
              <el-col :span="24" style="padding-top: 10px;padding-bottom: 10px">
                <el-button type="primary" v-bind:style="{display: isEditable == true ?'':'none'}" @click="handleAccountCostEdit(null,true,false,false)">新增费用</el-button>
              </el-col>
              <el-table :data="tableDataCostOtherList" highlight-current-row border show-summary :summary-method="getSummariesCostOther"
                        v-loading="listLoadingCostOther" style="width: 100%;margin-bottom: 10px;">
                <el-table-column type="index" width="50" label="序号" align="center">
                </el-table-column>
                <el-table-column prop="departureDate" label="发生日期" width="120"  align="center">
                  <template slot-scope="scope">
                    <label v-if="scope.row.occurredDate">{{scope.row.occurredDate.substring(0, 10)}}</label>
                  </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip fit prop="occurredOrgName" label="发生站点" width="150" header-align="center">
                </el-table-column>
                <el-table-column prop="billItem" label="计费项目" width="100"  align="center">
                  <template slot-scope="scope">
                    <label v-if="scope.row.billItem">{{scope.row.billItemName}}</label>
                  </template>
                </el-table-column>
                <el-table-column prop="fees" label="计费金额" width="120"  align="center">
                </el-table-column>
                <el-table-column prop="remark" label="备注" min-width="100"  align="center">
                </el-table-column>
                <el-table-column label="操作" width="210" align="center">
                  <template slot-scope="scope">
                    <el-button  type="primary" v-bind:style="{display: isEditable == true ?'':'none'}" style="margin-left: 0px;padding-left: 10px;padding-right: 10px"  @click="handleAccountCostEdit(scope.row.id,true,false,false)">编辑 </el-button>
                    <el-button  type="danger" v-bind:style="{display: isEditable == true ?'':'none'}"  style="margin-left: 0px;padding-left: 10px;padding-right: 10px" @click="handleAccountCostDelete(scope.row.id,false)">移除 </el-button>
                    <el-button  type="primary" @click="handleAccountCostPicture(scope.row.id)" style="margin-left: 0px;padding-left: 10px;padding-right:10px">单据详情 </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-col>
        <!--报账合计-->
        <el-col :span="24">
          <el-row style="padding: 10px;background-color: #F4FDFD;margin-bottom: 10px">
            <label style="font-weight: 700">报账合计: <label>{{this.commonParam.renderAccountSumOrder+this.commonParam.renderAccountSumOther}} 元</label></label>
          </el-row>
        </el-col>
      </el-row>
    </el-dialog>
    <!--订单费用记录弹窗-->
    <el-dialog title="订单费用记录" top="15%" size="large" :visible.sync="accountingCostListVisible"  @close='orderCostListCancel' :close-on-click-modal="false">
      <el-row>
      <el-col :span="24" style="margin-top: 10px">
          <div style="padding: 0px 10px">
            <label style="height: 35px;font-weight: 700">订单号：<label>{{orderNumber}}</label></label>
          </div>
          <div style="padding: 0px 10px 30px 10px">
            <el-row>
              <el-col :span="24" style="padding-top: 10px;padding-bottom: 10px">
                <el-button type="primary" v-bind:style="{display: isEditable == true ?'':'none'}" @click="handleAccountCostEdit(null,true,true,true)">新增费用</el-button>
              </el-col>
              <el-table :data="tableDataCostOrderList" highlight-current-row border show-summary :summary-method="getSummariesCostOrder"
                        v-loading="listLoadingCostOrder" style="width: 100%;margin-bottom: 10px;">
                <el-table-column type="index" width="50" label="序号" align="center">
                </el-table-column>
                <el-table-column prop="departureDate" label="发生日期" width="120"  align="center">
                  <template slot-scope="scope">
                    <label v-if="scope.row.occurredDate">{{scope.row.occurredDate.substring(0, 10)}}</label>
                  </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip fit prop="occurredOrgName" label="发生站点" width="150" header-align="center">
                </el-table-column>
                <el-table-column prop="billItem" label="计费项目" width="100"  align="center">
                  <template slot-scope="scope">
                    <label v-if="scope.row.billItem">{{scope.row.billItemName}}</label>
                  </template>
                </el-table-column>
                <el-table-column prop="fees" label="计费金额" width="120"  align="center">
                </el-table-column>
                <el-table-column prop="remark" label="备注" min-width="100"  align="center">
                </el-table-column>
                <el-table-column label="操作" width="210" align="center">
                  <template slot-scope="scope">
                    <el-button  type="primary" v-bind:style="{display: isEditable == true ?'':'none'}" style="margin-left: 0px;padding-left: 10px;padding-right: 10px" @click="handleAccountCostEdit(scope.row.id,true,true,true)">编辑 </el-button>
                    <el-button  type="danger" v-bind:style="{display: isEditable == true ?'':'none'}" style="margin-left: 0px;padding-left: 10px;padding-right: 10px"  @click="handleAccountCostDelete(scope.row.id,true)">移除 </el-button>
                    <el-button  type="primary"  @click="handleAccountCostPicture(scope.row.id)" style="margin-left: 0px;padding-left: 10px;padding-right: 10px">单据详情 </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </div>
      </el-col>
      </el-row>
    </el-dialog>
    <!--&lt;!&ndash;费用编辑弹窗&ndash;&gt;-->
    <el-dialog title="编辑费用"  :visible.sync="accountingCostEditVisible" @close='costCancel' :close-on-click-modal="false">
      <el-form :key="dialogKey"  ref="MRenderAccountCostForm" labelWidth="100px" label-position="right" :model="MRenderAccountCostForm" :rules="costRules">
        <el-row style="padding-top: 10px">
          <el-col :span="12">
            <el-form-item label="发生日期" prop="occurredDate" style="margin-bottom: 10px">
              <el-date-picker type="date" placeholder="选择发生日期" v-model="MRenderAccountCostForm.occurredDate" style="width: 95%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发生站点" prop="occurredOrgId" style="margin-bottom: 10px">
              <el-select v-model="MRenderAccountCostForm.occurredOrgId" style="width: 95%;" placeholder="请选择发生站点">
                <el-option
                  v-for="item in dischargeOrgList"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="padding-top: 10px">
          <el-col :span="12">
            <el-form-item label="计费项目" prop="billItem" style="margin-bottom: 10px">
              <el-select v-model="MRenderAccountCostForm.billItem" style="width: 95%"
                         placeholder="请选择报账状态">
                <el-option
                  v-for="orderSource in $store.getters.RENDER_ACCOUNT_BILL_ITEM"
                  :label="orderSource.cnDictValname"
                  :key="orderSource.dictVal"
                  :value="orderSource.dictVal"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="fees" style="margin-bottom: 10px">
              <el-input v-model.number="MRenderAccountCostForm.fees" type="number" style="width: 95%">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="padding-top: 10px">
          <el-form-item label="上传图片">
            <el-upload
              list-type="picture-card"
              ref="upload"
              action="/api/v2.0/admin/render_account_cost_picture/upload"
              :on-success="handlePreview"
              :before-upload="beforeAvatarUpload">
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">请上传有效费用单据图片，如中转托运单、转账记录单、现金付款单等，只能上传jpg/png文件，图片不超过5张，且不超过2M</div>
            </el-upload>
          </el-form-item>
        </el-row>
        <el-row style="padding-top: 10px">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea"
                      :autosize="{ minRows: 3, maxRows: 3}" v-model="MRenderAccountCostForm.remark"
                      placeholder="请输入备注"  style="width: 95%"></el-input>
          </el-form-item>
        </el-row>
        <el-row style="text-align: center">
          <el-form-item>
            <el-button type="primary" style="width: 100px;padding-top: 10px;padding-bottom: 10px" :disabled="!isCostEdit" @click="submitCostSave" :loading="submitLoading"> 保 存 </el-button>
            <!--<el-button type="primary"  style="width: 100px;padding-top: 10px;padding-bottom: 10px" :disabled="!isCostEdit" @click="submitCostNew()" :loading="submitLoading"> 新 增 </el-button>-->
            <el-button  style="width: 100px;padding-top: 10px;padding-bottom: 10px" @click="costCancel()"> 关 闭 </el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>

    <!--查看单据 弹窗-->
    <el-dialog title="单据详情" size="tiny" :visible.sync="pictureVisible" @close='costPictureCancel'
               :close-on-click-modal="false">
      <el-form label-width="100px">
        <template v-for="(item,index) in costPictureArray">
          <li :key="index">
            <img width="100%" height="100%" v-bind:src="item">
          </li>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="costPictureCancel()">取消</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import {
  searchRenderAccounts,
  modifyStatus,
  searchRenderAccountDetails,
  searchRenderAccountCostsOther,
  saveRenderAccountCost,
  deleteRenderAccountCost,
  getRenderAccountCost,
  searchRenderAccountCostsOrder,
  getCostPicture,
  getDischargeOrgList
} from '../../api/accounting/RenderAccount';
import {isEmpty, getSelectObect} from '../../lib/util';
export default {
  data () {
    return {
      isNotAuditor: '',
      isEditable: false, // 是否可编辑-费用增改
      isAuditor: true,
      isAuditorOrg: false,
      dischargeOrgList: [], // 下货组织
      commonParam: {
        renderAccountSumOrder: 0,
        renderAccountSumOther: 0,
        renderAccountDetailIdOther: '',
        renderAccountDetailIdOrder: '',
        renderAccountDetailIdCurrent: '',
        renderAccountId: '',
        isRefreshOrderCostList: false
      },
      currentOrganizationId: this.$store.state.currentOrganizationId,
      currentOrganizationName: '',
      // 报账主页
      isLast: false, // 是否最后下货组织
      toAffirm: false, //  费用确认
      cancelAffirm: false, // 取消确认
      toAudit: false, // 提交审核
      cancelAudit: false, // 取消提交审核
      toAffirmAudit: false, // 确认审核
      toRefuseAudit: false, // 驳回
      toCancelAffirmAudit: false, // 取消确认审核
      dateNow: new Date(),
      searchConditionForm: {
        dateType: 'departureDate',
        dateTypeValueStart: this.dateNow,
        dateTypeValueEnd: this.dateNow,
        driverOrVehicle: 'plateNumber',
        driverOrVehicleValue: null,
        status: null,
        departureOrgName: null
      },
      //  分页信息
      sels: [],
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: 'departureDate',
      sortOrder: 'descending',
      listLoading: false,
      // 报账明细弹窗
      accountingDetailVisible: false,
      selsDetail: [],
      tableDataDetail: [],
      totalDetail: 0,
      currentPageDetail: 1,
      pageSizeDetail: 10,
      sortPropDetail: null,
      sortOrderDetail: 'descending',
      listLoadingDetail: false,
      tableDataCostOtherList: [],
      listLoadingCostOther: false,
      // 订单费用记录弹窗
      orderNumber: '',
      accountingCostListVisible: false,
      tableDataCostOrderList: [],
      listLoadingCostOrder: false,
      // 其他费用明细
      // 费用编辑弹窗
      pictureVisible: false,
      costPictureArray: [],
      fileList: [],
      dialogKey: 0,
      isCostEdit: true,
      accountingCostEditVisible: false,
      submitLoading: false,
      // 费用明细
      MRenderAccountCostForm: {
        'id': '',
        'renderAccountDetailId': null,
        'occurredDate': null,
        'occurredOrgId': this.currentOrganizationId,
        'occurredOrgName': null,
        'billItem': null,
        'fees': null,
        'remark': null,
        renderAccountCostPicture: {
          'id': null,
          'pictureUrl': null
        }
      },
      costRules: {
        occurredDate: [
          {required: true, message: '请输入发生日期'}
        ],
        occurredOrgId: [
          {required: true, message: '请选择发生站点'}
        ],
        billItem: [
          {required: true, message: '请选择计费项目'}
        ],
        fees: [
          {required: true, message: '请输入金额'}
        ]
      }
    };
  },
  methods: {
    // 报账主页面----
    // 今天
    searchToday () {
      this.searchConditionForm.dateTypeValueStart = this.dateNow;
      this.searchConditionForm.dateTypeValueEnd = this.dateNow;
    },
    // 这一周
    searchWeek () {
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      this.searchConditionForm.dateTypeValueStart = start;
      this.searchConditionForm.dateTypeValueEnd = this.dateNow;
    },
    // 这一月
    searchMonth () {
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      this.searchConditionForm.dateTypeValueStart = start;
      this.searchConditionForm.dateTypeValueEnd = this.dateNow;
    },
    // 报账明细
    handleAccountDetail (row) {
      if (this.currentOrganizationId === row.organizationId) {
        this.isAuditorOrg = true;
      } else {
        this.isAuditorOrg = false;
      }
      if (row.accountingOrgId === this.currentOrganizationId) {
        this.isLast = true;
      } else {
        this.isLast = false;
      }
      this.accountingDetailVisible = true;
      this.commonParam.renderAccountId = row.id;
      this.getRenderAccountDetail(row.id);
      this.getRenderAccountCostOtherList(row.id);
      this.getDischargeOrgListCurrDetail(row.id);
    },
    detailListCancel () {
      this.isAuditorOrg = false;
      this.isLast = false;
      this.commonParam.renderAccountSumOrder = 0;
      this.commonParam.renderAccountSumOther = 0;
      this.getTableData();
    },
    // 选择行操作
    selsChange (sels) {
      this.sels = sels;
      this.isLast = false;
      this.toAffirm = false;
      this.cancelAffirm = false;
      this.toAudit = false;
      this.cancelAudit = false;
      this.toAffirmAudit = false;
      this.toRefuseAudit = false;
      this.toCancelAffirmAudit = false;
      if (this.currentOrganizationId === sels.organizationId) {
        this.isNotAuditor = 'none';
        this.isAuditor = true;
        this.isEditable = false;
      } else {
        this.isNotAuditor = '';
        this.isAuditor = false;
        if (sels.status === 102016001) {
          this.isEditable = true;
        } else {
          this.isEditable = false;
        }
      }
      // 操作按钮显示
      // 当前组织为最后一个组织可进行费用确认，取消确认操作
      if (sels.accountingOrgId === this.currentOrganizationId) {
        this.isLast = true;
      } else {
        this.isLast = false;
      }
      if (this.isLast && sels.status === 102016001) {
        this.toAffirm = true;
        return;
      }
      if (this.isLast && sels.status === 102016002) {
        this.cancelAffirm = true;
        this.toAudit = true;
        return;
      }
      if (this.isLast && sels.status === 102016003) {
        this.cancelAudit = true;
        return;
      }
      if (this.isLast && sels.status === 102016005) {
        this.cancelAffirm = true;
        this.toAudit = true;
        return;
      }
      if (this.isAuditor && sels.status === 102016003) {
        this.toAffirmAudit = true;
        this.toRefuseAudit = true;
        return;
      }
      if (this.isAuditor && sels.status === 102016004) {
        this.toCancelAffirmAudit = true;
      }
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.getTableData();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.getTableData();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.getTableData();
    },
    // 重置查询条件
    resetCondition () {
      this.searchConditionForm = {
        dateType: 'departureDate',
        dateTypeValueStart: null,
        dateTypeValueEnd: null,
        driverOrVehicle: 'plateNumber',
        driverOrVehicleValue: null,
        status: null,
        departureOrgName: null
      };
    },
    // 修改报账单状态（费用确认、取消确认、提交审核，取消提交审核）
    modifyStatus (status, statusName) {
      modifyStatus({id: this.sels.id, status: status}).then((res) => {
        this.listLoading = false;
        if (res.data.successFlg === true) {
          this.sels.statusName = statusName;
          this.sels.status = status;
          let info = res.data.obj;
          let affirmTime = '';
          if (info.affirmTime) {
            affirmTime = info.affirmTime.substring(0, 10);
          }
          this.sels.affirmTime = affirmTime;
          let auditTime = '';
          if (info.auditTime) {
            auditTime = info.auditTime.substring(0, 10);
          }
          this.sels.auditTime = auditTime;
          this.selsChange(this.sels);
          this.$message.success('操作成功');
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    // 获取表格数据
    getTableData () {
      let filters = '';
      if (!isEmpty(this.searchConditionForm.dateTypeValueStart)) {
        filters += 'GTE_' + this.searchConditionForm.dateType + '=' + this.searchConditionForm.dateTypeValueStart.toJSON().substring(0, 10) + ' 00:00:00 ;';
      }
      if (this.searchConditionForm.dateTypeValueStart > this.searchConditionForm.dateTypeValueEnd) {
        this.$message.error('结束日期不能早于开始日期');
        return;
      }
      if (!isEmpty(this.searchConditionForm.dateTypeValueEnd)) {
        filters += 'LTE_' + this.searchConditionForm.dateType + '=' + this.searchConditionForm.dateTypeValueEnd.toJSON().substring(0, 10) + ' 23:59:59 ;';
      }
      if (!isEmpty(this.searchConditionForm.driverOrVehicleValue)) {
        filters += 'LIKE_' + this.searchConditionForm.driverOrVehicle + '=' + this.searchConditionForm.driverOrVehicleValue + ' ;';
      }
      if (!isEmpty(this.searchConditionForm.status)) {
        filters += 'EQ_status=' + this.searchConditionForm.status + ' ;';
      }
      if (!isEmpty(this.searchConditionForm.departureOrgName)) {
        filters += 'LIKE_departureOrgName=' + this.searchConditionForm.departureOrgName + ' ;';
      }
      this.listLoading = true;
      searchRenderAccounts({
        page: this.currentPage,
        size: this.pageSize,
        filters: filters,
        sorts: (isEmpty(this.sortProp) ? '' : (this.sortOrder === 'ascending' ? '+' : '-') + this.sortProp)
      }).then((res) => {
        this.listLoading = false;
        if (res.data.successFlg === true) {
          if (res.data.detailModelList != null) {
            this.tableData = res.data.detailModelList;
            this.currentPage = res.data.currPage;
            this.total = res.data.totalCount;
            this.pageSize = res.data.pageSize;
          } else {
            this.tableData = [];
          }
          this.listLoading = false;
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    // 获取下货机构列表
    getDischargeOrgListCurrDetail (renderAccountId) {
      getDischargeOrgList({id: renderAccountId}).then((res) => {
        if (res.data.successFlg) {
          this.dischargeOrgList = res.data.detailModelList;
        }
      });
    },
    // 排序操作
    sortChangeDetail (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.getTableData();
    },
    // 每页几条操作
    handleSizeChangeDetail (val) {
      this.pageSize = val;
      this.getTableData();
    },
    // 第几页操作
    handleCurrentChangeDetail (val) {
      this.currentPage = val;
      this.getTableData();
    },
    // 费用记录
    handleAccountCostList (row) {
      this.accountingCostListVisible = true;
      this.orderNumber = row.orderNumber;
      this.commonParam.renderAccountDetailIdOrder = row.id;
      this.commonParam.renderAccountDetailIdCurrent = row.id;
      this.getRenderAccountCostOrderList(row.id);
    },
    orderCostListCancel () {
      this.getRenderAccountDetail(this.commonParam.renderAccountId);
    },
    // 费用明细增改-订单费用
    handleAccountCostEdit (costDetailId, isEdit, isOrderCost, isRefreshOrderCostList) {
      this.dialogKey = Math.random() - 0.5;
      this.accountingCostEditVisible = true;
      if (isEdit) {
        this.isCostEdit = true;
      } else {
        this.isCostEdit = false;
      }
      if (isOrderCost) {
        this.commonParam.renderAccountDetailIdCurrent = this.commonParam.renderAccountDetailIdOrder;
      } else {
        this.commonParam.renderAccountDetailIdCurrent = this.commonParam.renderAccountDetailIdOther;
      }
      this.commonParam.isRefreshOrderCostList = isRefreshOrderCostList;
      if (costDetailId) {
        // 获取费用信息
        this.getRenderAccountCostDetail(costDetailId);
      }
    },
    // 单据详情
    handleAccountCostPicture (costDetailId) {
      this.pictureVisible = true;
      getCostPicture({costId: costDetailId}).then((res) => {
        if (res.data.successFlg && res.data.obj != null) {
          if (res.data.obj.pictureUrl) {
            this.costPictureArray = res.data.obj.pictureUrl.split(',');
          }
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    costPictureCancel () {
      this.pictureVisible = false;
    },
    // 获取报账明细
    getRenderAccountDetail (renderAccountId) {
      let filters = 'EQ_renderAccountId=' + renderAccountId + ';EQ_detailType=111002001;';
      if (!(this.isLast) && !(this.isAuditorOrg)) {
        filters += 'EQ_dischargeOrgId=' + this.currentOrganizationId + ';';
      };
      this.listLoadingDetail = true;
      searchRenderAccountDetails({
        page: this.currentPageDetail,
        size: this.pageSizeDetail,
        filters: filters,
        sorts: (this.sortPropDetail === null ? '' : (this.sortOrderDetail === 'ascending' ? '+' : '-') + this.sortPropDetail)
      }).then((res) => {
        this.listLoadingDetail = false;
        if (res.data.successFlg) {
          if (res.data.detailModelList != null) {
            this.tableDataDetail = res.data.detailModelList;
            this.currentPageDetail = res.data.currPage;
            this.totalDetail = res.data.totalCount;
            this.pageSizeDetail = res.data.pageSize;
          } else {
            this.tableDataDetail = [];
          }
          this.listLoadingDetail = false;
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    // 获取订单费用明细
    getRenderAccountCostOrderList (detailId) {
      let filters = 'EQ_renderAccountDetailId=' + detailId + ';';
      searchRenderAccountCostsOrder({
        filters: filters,
        sorts: ''
      }).then((res) => {
        if (res.data.successFlg) {
          if (res.data.detailModelList != null) {
            this.tableDataCostOrderList = res.data.detailModelList;
          } else {
            this.tableDataCostOrderList = [];
          }
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    // 获取其他费用明细
    getRenderAccountCostOtherList (renderAccountId) {
      let filters = '';
      this.listLoadingCostOther = true;
      searchRenderAccountCostsOther({
        filters: filters,
        sorts: '',
        renderAccountId: renderAccountId
      }).then((res) => {
        this.listLoadingCostOther = false;
        this.commonParam.renderAccountDetailIdOther = res.data.obj.renderAccountDetailId;
        if (res.data.successFlg) {
          if (res.data.detailModelList != null && res.data.detailModelList.length > 0) {
            this.tableDataCostOtherList = res.data.detailModelList;
          } else {
            this.tableDataCostOtherList = [];
            this.commonParam.renderAccountSumOther = 0;
          }
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    // 费用明细移除
    handleAccountCostDelete (costDetailId, isRefreshOrderCostList) {
      this.$confirm('确认移除该费用明细?', '提示', {
        type: 'warning'
      }).then(() => {
        deleteRenderAccountCost({ids: costDetailId}).then((res) => {
          if (res.data.successFlg) {
            this.$message.success('操作成功');
            if (isRefreshOrderCostList) {
              this.getRenderAccountCostOrderList(this.commonParam.renderAccountDetailIdOrder);
            } else {
              this.getRenderAccountCostOtherList(this.commonParam.renderAccountId);
            }
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
      }).catch(() => {
      });
    },
    // 订单费用记录弹窗---
    // 费用编辑弹窗---
    handlePreview (file) {
      this.fileList.push(file.obj);
    },
    // 图片上传限制
    beforeAvatarUpload (file) {
      let isJPG = false;
      if (file.type) {
        const fileTypes = 'image/jpeg;image/png;image/bmp;image/tiff;image/wmf';
        isJPG = fileTypes.indexOf(file.type) !== -1;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/BMP/TIFF/WMF 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 获取费用明细详情
    getRenderAccountCostDetail (costDetailId) {
      getRenderAccountCost({id: costDetailId}).then((res) => {
        let info = res.data.obj;
        if (res.data.successFlg && info !== null) {
          this.MRenderAccountCostForm = {
            'id': info.id,
            'renderAccountDetailId': info.renderAccountDetailId,
            'occurredDate': info.occurredDate,
            'occurredOrgId': info.occurredOrgId,
            'occurredOrgName': info.occurredOrgName,
            'billItem': info.billItem,
            'fees': info.fees,
            'remark': info.remark,
            'renderAccountCostPicture': {
              'id': null,
              'pictureUrl': null
            }
          };
          let costPicture = info.renderAccountCostPicture;
          if (costPicture) {
            this.MRenderAccountCostForm.renderAccountCostPicture = {
              'id': costPicture.id,
              'pictureUrl': costPicture.pictureUrl
            };
          }
        } else {
          this.$message.error(res.data.errorMsg);
        }
      }).catch(function (error) {
        console.log(error);
      });
    },
    // 关闭
    costCancel () {
      console.log('11');
      this.accountingCostEditVisible = false;
      this.commonParam.renderAccountDetailIdCurrent = '';
      this.fileList = [];
      this.MRenderAccountCostForm = {
        'id': '',
        'renderAccountDetailId': null,
        'occurredDate': null,
        'occurredOrgId': this.occurredOrgId,
        'occurredOrgName': this.currentOrganizationName,
        'billItem': null,
        'fees': null,
        'remark': null,
        'renderAccountCostPicture': {
          'id': null,
          'pictureUrl': null
        }
      };
    },
    // 保存
    submitCostSave () {
      this.submit();
    },
    // 新增
    submitCostNew () {
      this.MRenderAccountCostForm.id = '';
      this.MRenderAccountCostForm.renderAccountCostPicture.id = '';
      this.submit();
    },
    submit () {
      // 表单验证
      this.$refs['MRenderAccountCostForm'].validate((valid) => {
        this.MRenderAccountCostForm.renderAccountDetailId = this.commonParam.renderAccountDetailIdCurrent;
        if (this.fileList.length > 0) {
          this.MRenderAccountCostForm.renderAccountCostPicture.pictureUrl = this.fileList.join(',');
        }
        if (valid) {
          this.submitLoading = true;
          this.MRenderAccountCostForm.occurredOrgName = getSelectObect(this.MRenderAccountCostForm.occurredOrgId, 'value', this.dischargeOrgList).text;
          saveRenderAccountCost(this.MRenderAccountCostForm).then((res) => {
            this.submitLoading = false;
            if (res.data.successFlg) {
              this.MRenderAccountCostForm.id = res.data.obj.id;
              this.MRenderAccountCostForm.renderAccountCostPicture.id = res.data.obj.renderAccountCostPicture.id;
              this.$message.success('操作成功');
              this.costCancel();
              if (this.commonParam.isRefreshOrderCostList) {
                this.getRenderAccountCostOrderList(this.commonParam.renderAccountDetailIdOrder);
              } else {
                this.getRenderAccountCostOtherList(this.commonParam.renderAccountId);
              }
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            console.log(error);
          });
        } else {
          this.$message.error('数据有误');
          return false;
        }
      });
    },
    getSummariesCostOrder (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '小计';
          return;
        }
        if (index !== 4) {
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });
      return sums;
    },
    getSummariesCostOther (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '小计';
          return;
        }
        if (index !== 4) {
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          this.commonParam.renderAccountSumOther = sums[4];
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });
      return sums;
    },
    getSummariesDetail (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '小计';
          return;
        }
        if (index !== 7) {
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          this.commonParam.renderAccountSumOrder = sums[7];
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },
    getSummariesAccount (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '报账总计';
          return;
        }
        if (index !== 6) {
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          this.commonParam.renderAccountDetailIdOrder = sums[7];
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    }
  },
  mounted () {
    this.$store.commit('initDict');
    this.getTableData();
  }
};
</script>
